<template>
    <div class="variable-page" :style="{ transform: firstShow && show ? 'translateX(0)' : '' }" v-click-outside="onClickBodyOut"
        :class="[isShowArrow && 'variable-fixed']">
        <div class="variable-tilte">
            <div class="name">
                <span>{{ $t('message.form.variableConfiguration') }}</span>
                <svg class="hidden-icon" v-if="isShowArrow" @click="showArrowButton">
                    <use xlink:href="#keowledge-shousuo"></use>
                </svg>
            </div>
            <svg class="close-icon" @click="closeVersion">
                <use xlink:href="#keowledge-danchuangguanbi1"></use>
            </svg>
        </div>
        <div class="save-path-box">
            <div class="title">{{ $t('message.text.fileStoreInfo') }}</div>
            <div class="path-box" @click="openSelectFile">
                <svg class="dir-icon">
                    <use xlink:href="#keowledge-wenjian"></use>
                </svg>
                <span class="dir-name">{{ templateInfo.savePathName || $t('message.text.pleaseStorageLocation') }}</span>
                <svg class="arrow-icon">
                    <use xlink:href="#keowledge-a-zu4701"></use>
                </svg>
            </div>
        </div>
        <div class="var-title">
            <div class="name">{{ $t('message.text.variableInfo') }}</div>
            <svg class="button-box" @click="addVar">
                <use xlink:href="#keowledge-tianjia1"></use>
            </svg>
        </div>
        <div class="variable-content">
            <el-scrollbar ref="variableScrollRef">
                <div class="var-item" v-for="(item, index) in variaList" :key="index">
                    <div class="var-input-box">
                        <el-select class="var-type" v-model="item.type" @change="submitVal(index)">
                            <el-option :label="$t('message.typeMenu.text')" value="STRING"></el-option>
                            <el-option :label="$t('message.beCurrent.image')" value="IMAGE"></el-option>
                        </el-select>
                        <el-input class="var-name" v-model="item.name"
                            :placeholder="$t('message.placeholder.pleaseVarible')" @blur="submitVal(index)"
                            @keydown.enter="submitVal(index)"></el-input>
                    </div>
                    <div class="var-action-box">
                        <svg class="action-item" @click="doAction('copy', index)">
                            <use xlink:href="#keowledge-a-huaban18"></use>
                        </svg>
                        <svg class="action-item" @click="doAction('del', index)">
                            <use xlink:href="#keowledge-jian"></use>
                        </svg>
                    </div>
                </div>
            </el-scrollbar>
        </div>
    </div>
    <selectKnow ref="saveKnowRef" :title="$t('message.text.saveLocation')" @callBack="getCheckedFile"></selectKnow>
</template>

<script setup lang="ts">
import {
    ref,
    reactive,
    toRefs,
    watch,
    onMounted,
    nextTick,
    getCurrentInstance
} from 'vue'
import type { ComponentInternalInstance } from 'vue'
import selectKnow from '@/views/selectKnow/index.vue'
import { useRouter } from "vue-router"
import { saveTempFilePath, getAllVariable, delVariable, addOrEditVar } from '@/api/template'
import { copyText } from '@/utils/util'
const router = useRouter();
import { useHookI18n } from '@/hooks/i18n'
const { locale, $t } = useHookI18n()
const emit = defineEmits(["close", "changeArrow"])
const variableScrollRef = ref()
const instance: any = getCurrentInstance() as ComponentInternalInstance;
const proxy: any = instance.proxy as any; // 访问 proxy 属性
const props = defineProps({
    show: {
        type: Boolean,
        default: false
    },
    isShowArrow: {
        type: Boolean,
        default: false
    },
    docInfo: {
        type: Object,
        default: () => {
            return {}
        }
    },
    isIframe: {
        type: Boolean,
        default: false
    }
})
const variaList = ref([])
const copyVariaList = ref([])
const firstShow = ref(false)
const templateInfo = ref({})
const saveKnowRef = ref()
const varLoading = ref(false)
onMounted(() => {
    templateInfo.value = props.docInfo
    init()
    varLoading.value = true
    nextTick(() => {
        firstShow.value = true
    })
})
function init() {
    getAllVariable({ templateId: props.docInfo.id }, props.isIframe).then(res => {
        if (res.data.code == 0) {
            variaList.value = JSON.parse(JSON.stringify(res.data.data[0]?.variableList || []))
            variaList.value.forEach((item, index) => {
                if (!item.type) {
                    item.type = 'STRING'
                }
            })
            copyVariaList.value = JSON.parse(JSON.stringify(variaList.value))
        } else {
            proxy.$onePrompt.$oneNotify({
                title: $t('message.prompt'),
                message: (res.data.msg),
                type: 'warning',
                position: 'bottom-right'
            });
        }
    }).finally(res => {
        varLoading.value = false
    })
}
// 新增变量
function addVar() {
    variaList.value.push({
        name: '',
        type: "STRING"
    })
    copyVariaList.value.push({
        name: '',
        type: "STRING"
    })
}
function getCheckedFile(val) {
    saveTempFilePath({
        ...templateInfo.value,
        savePathId: val.id,
        savePathName: val.name
    }, props.isIframe).then(res => {
        if (res.data.code == 0) {
            templateInfo.value.savePathId = val.id
            templateInfo.value.savePathName = val.name
        } else {
            proxy.$onePrompt.$oneNotify({
                title: $t('message.prompt'),
                message: res.data.msg,
                type: 'warning',
                position: 'bottom-right'
            });
        }
    })
}
function submitVal(index) {
    if (variaList.value[val].name != copyVariaList.value[val].name && variaList.value[val].name || variaList.value[val].type != copyVariaList.value[val].type) {
        addOrEditVar({
            templateId: props.docInfo.id,
            ...variaList.value[val]
        }, props.isIframe).then(res => {
            if (res.data.code == 0) {
                variaList.value[val].id = res.data.data.id
                variaList.value[val].templateId = res.data.data.templateId
                copyVariaList.value[val].id = res.data.data.id
                copyVariaList.value[val].name = res.data.data.name
                copyVariaList.value[val].templateId = res.data.data.templateId
                copyVariaList.value[val].type = res.data.data.type
            } else {
                proxy.$notify({
                    title: $t('message.prompt'),
                    message: (res.data.msg),
                    type: 'warning',
                    position: 'bottom-right'
                });
            }
        })
    }
}
function doAction(type, index) {
    switch (type) {
        case 'copy':
            let str = variaList.value[index].type == 'STRING' ? `\{\{${variaList.value[index].name}\}\}` : `\{\{@${variaList.value[index].name}\}\}`
            copyText(str, () => {
                proxy.$notify({
                    title: $t('message.message.copySuccess'),
                    type: 'success',
                    position: 'bottom-right'
                });
            })
            break;
        case 'del':
            if (variaList.value[index].id) {
                delVariable({
                    id: variaList.value[index].id
                }, props.isIframe).then(res => {
                    if (res.data.code == 0) {
                        variaList.value.splice(index, 1)
                        copyVariaList.value.splice(index, 1)
                    } else {
                        proxy.$onePrompt.$oneNotify({
                            title: $t('message.prompt'),
                            message: (res.data.msg),
                            type: 'warning',
                            position: 'bottom-right'
                        });
                    }
                })
            } else {
                variaList.value.splice(index, 1)
                copyVariaList.value.splice(index, 1)
            }
            break
        default:
            break;
    }
}
function openSelectFile() {
    saveKnowRef.value.init()
}
function closeVersion() {
    emit("close")
}
function showArrowButton() {
    emit('changeArrow', true)
}
function onClickBodyOut() {
    if (props.isShowArrow) {
        showArrowButton()
    }
}
</script>
<style lang="scss" scoped>
.variable-page {
    min-width: 240px;
    height: 100%;
    width: 240px;
    background-color: #fff;
    transition: transform .2s;
    user-select: none;
    transform: translateX(100%);

    .variable-tilte {
        padding: 16px 0px;
        margin: 0px 16px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        border-bottom: 1px solid #EEEFF0;

        .name {
            display: flex;
            align-items: center;
            font-size: 16px;
            color: #363b4c;

            span {
                @include SourceHanSansCN-Bold;
            }

            .hidden-icon {
                width: 16px;
                height: 16px;
                cursor: pointer;
            }
        }

        .close-icon {
            width: 16px;
            height: 16px;
            cursor: pointer;
        }
    }

    .save-path-box {
        padding: 16px 0;
        margin: 0px 16px;
        border-bottom: 1px solid #eeeff0;

        .title {
            color: #363b4c;
            font-size: 14px;
            @include SourceHanSansCN-Medium;
            margin-bottom: 8px
        }

        .path-box {
            width: 100%;
            height: 36px;
            background: #F5F6F7;
            border-radius: 4px 4px 4px 4px;
            display: flex;
            align-items: center;
            padding: 0px 8px 0px 16px;
            justify-content: space-between;
            cursor: pointer;

            .dir-icon {
                width: 16px;
                height: 16px;
                min-width: 16px;
            }

            .dir-name {
                text-overflow: ellipsis;
                overflow: hidden;
                white-space: nowrap;
            }

            .arrow-icon {
                min-width: 16px;
                width: 16px;
                height: 16px;
            }
        }
    }

    .var-title {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 16px;

        .name {
            font-size: 14px;
            color: #363b4c;
            @include SourceHanSansCN-Medium;
        }

        .button-box {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 16px;
            height: 16px;
            font-size: 14px;
            color: #fff;
            border-radius: 3px;
            background-color: #1E6FFF;
            cursor: pointer;
        }
    }

    .variable-content {
        height: calc(100vh - 215px);
        background-color: #fff;

        .var-item {
            margin: 0px 16px;
            display: flex;
            align-items: center;
            justify-content: center;

            .var-input-box {
                background: #F5F6F7;
                border-radius: 4px 4px 4px 4px;
                overflow: hidden;
                display: flex;
                align-items: center;

                .var-type {
                    width: 64px;
                    min-width: 64px;
                    background-color: #eeeff0;

                    ::v-deep(.el-input__wrapper) {
                        padding: 1px 5px 1px 11px !important;
                    }
                }

                .var-name {}

                ::v-deep(.el-input__wrapper) {
                    box-shadow: none !important;
                    border: none !important;
                    background: transparent !important;

                    .el-icon {
                        margin-left: 0px !important;
                    }
                }
            }

            .var-action-box {
                display: flex;
                align-items: center;

                .action-item {
                    margin-left: 8px;
                    width: 16px;
                    height: 16px;
                    cursor: pointer;
                    border-radius: 4px;
                    display: flex;
                    align-items: center;
                }
            }
        }

        .var-item+.var-item {
            margin-top: 16px;
        }
    }
}

.variable-fixed {
    position: fixed;
    right: 0px;
    z-index: 200;
    background-color: #fff;
    box-shadow: 0px 1px 10px 0px rgba(54, 59, 76, 0.15);
}
</style>